/*
 *
 *  *    Copyright 2020-2021 Luter.me
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 *
 */

package com.luter.heimdall.core.token;

import com.luter.heimdall.core.config.HeimdallProperties;
import com.luter.heimdall.core.context.WebContextHolder;
import com.luter.heimdall.core.cookie.SimpleCookie;
import com.luter.heimdall.core.exception.HeimdallException;
import com.luter.heimdall.core.utils.StrUtils;
import com.luter.heimdall.core.utils.crypto.Md5Util;
import org.slf4j.Logger;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * TokenStore 帮助类
 *
 * @author luter
 */
public abstract class TokenHelper {
    /**
     * The constant log.
     */
    private static final transient Logger log = getLogger(TokenHelper.class);

    /**
     * Instantiates a new Token helper.
     */
    private TokenHelper() {
    }

    /**
     * 设置客户端 IP
     *
     * @param webContextHolder the web context holder
     * @param token            the token
     * @return the ria
     */
    public static SimpleToken setRia(WebContextHolder webContextHolder, SimpleToken token) {
        log.debug("[setRia]::token = [{}]", token);
        if (null != webContextHolder) {
            if (StrUtils.isBlank(token.getRia())) {
                final String remoteIp = webContextHolder.getRequest().getRemoteIp();
                log.info("[setRia]:: Get Remote Ip,IP=[{}], token = [{}]", remoteIp, token);
                return token.setRia(Md5Util.encrypt(remoteIp));
            }
        } else {
            log.warn("[setRia]:: The webContextHandler is not set correctly, " +
                    "unable to get the IP address for Token . token = [{}]", token);
        }
        return token;
    }

    /**
     * 往 response 写入 cookie
     * <p>
     * cookie开启且 jwt 的白名单未开启的情况下有效
     *
     * @param config the config
     * @param token  the token
     */
    public static void addCookie(WebContextHolder webContextHolder, HeimdallProperties config, SimpleToken token) {
        //写入 cookie
        //cookie开启且 jwt 的白名单未开启
        if (config.getCookie().isEnabled() && !config.getJwt().isWhiteList()) {
            log.debug("[addCookie]::Cookie is enabled. token = [{}]", token);
            if (null != webContextHolder) {
                SimpleCookie cookie = new SimpleCookie(token.getId());
                webContextHolder.getResponse().setHeader(SimpleCookie.COOKIE_HEADER_NAME, cookie.toString());
                log.info("[addCookie]::Set Cookie to Response.token = [{}],cookie = [{}={}],cookieString=[{}]", token,
                        config.getToken().getName(), token.getId(), cookie);
            } else {
                String err = "Cookie is enabled, but the WebContextHolder is not provided." +
                        " As a result, the cookie function will be disabled.";
                log.error(err);
                throw new HeimdallException(err);
            }
        } else {
            log.debug("[addCookie]::Cookie is Disabled.token = [{}]", token);
        }
    }
}
